#include "ulibc.h"

#define N 8

void run();

void main() {
	init();
	run();
	exit();
}

void lines(int y, uchar c, uint count, struct gfx_context *context) {
	int i, j;
	for (j = 0; j < count; j++) {
		for (i = 0; i < context->line_size; i++)
			gfx_setpixel4(i << 2, y + j, c + j, context);
	}
}

void run() {
	struct gfx_context context;
	// sinus table
	static int sin[256] = {100,102,104,107,109,112,114,117,119,121,124,126,129,131,133,136,138,140,142,145,147,149,151,153,155,157,159,161,163,165,167,169,170,172,174,175,177,179,180,181,183,184,185,187,188,189,190,191,192,193,194,195,195,196,197,197,198,198,198,199,199,199,199,199,199,199,199,199,199,199,198,198,197,197,196,196,195,194,193,193,192,191,190,188,187,186,185,184,182,181,179,178,176,175,173,171,170,168,166,164,162,160,158,156,154,152,150,148,146,144,141,139,137,134,132,130,127,125,123,120,118,115,113,111,108,106,103,101,98,96,93,91,88,86,84,81,79,76,74,72,69,67,65,62,60,58,55,53,51,49,47,45,43,41,39,37,35,33,31,29,28,26,24,23,21,20,18,17,15,14,13,12,11,9,8,7,6,6,5,4,3,3,2,2,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,4,4,5,6,7,8,9,10,11,12,14,15,16,18,19,20,22,24,25,27,29,30,32,34,36,38,40,42,44,46,48,50,52,54,57,59,61,63,66,68,70,73,75,78,80,82,85,87,90,92,95,97,99};
	int t[N], y[N], i, page;

	gfx_init320x240(&context);

	for (i = 0; i < N; i++) {
		int j = i * 7;
		t[i] = umod(i*6+192,256);
	}

	page = 0;

	while (1) {
		if (is_keypressed()) {
			uchar c = read_char();
			if (c == 'q') break;
		}

		gfx_showpage(page, &context);
		gfx_setpage(page ^ 1, &context);
		gfx_clearpage(0, &context);
		for (i = 0; i < N; i++) {
			y[i] = sin[t[i]];
			lines(y[i] + 20, i + 32, 3, &context);
			t[i] = (t[i] + 2) & 255;
		}

		gfx_print_string(80,100,24,"Bouncing bars demo",&context);
		gfx_print_string(80,114,24,"Press 'q' to quit...",&context);

		page ^= 1;
	}

	gfx_close();
}
